<template>
  <div :class="['vt-radio-group', { 'vt-radio-group-start': start }]">
    <!-- 多选模式 -->
    <el-checkbox-group v-if="multiple" v-model="selectedValues" @change="handleChange">
      <div v-for="item in options" :key="item.id || item.value" class="radio-item">
        <el-checkbox :value="item.value" :disabled="disabled">
          {{ item.label }}
        </el-checkbox>

        <!-- 材质类型显示厚度输入框（仅当editable=1时） -->
        <el-input-number
          v-if="type === 'material' && isMaterialSelected(item.value) && item.editable === 1"
          :model-value="getMaterialThickness(item.value)"
          class="thickness-input"
          placeholder="厚度"
          :min="0"
          :precision="2"
          size="small"
          @change="handleThicknessChange(item.value, $event)"
        >
          <template #append>mm</template>
        </el-input-number>
      </div>
    </el-checkbox-group>

    <!-- 单选模式 -->
    <el-radio-group v-else v-model="singleValue" @change="handleSingleChange">
      <div v-for="item in options" :key="item.id || item.value" class="radio-item">
        <el-radio :value="item.value" :disabled="disabled">
          {{ item.label }}
        </el-radio>
      </div>
    </el-radio-group>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useVtOptionsStore } from "@/store/modules/vt-options.store.js";

defineOptions({
  name: "VtRadioGroup",
  inheritAttrs: false,
});

const props = defineProps({
  modelValue: {
    type: [Array, String],
    default: () => [],
  },
  type: {
    type: String,
    required: true,
    validator: (value) =>
      ["bagType", "compositeType", "material", "size", "surfaceFee", "accessory"].includes(value),
  },
  filterType: {
    type: Number,
    default: null,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  start: {
    type: Boolean,
    default: false,
  },
  multiple: {
    type: Boolean,
    default: true,
  },
});

const emit = defineEmits(["update:modelValue", "change"]);

const vtOptionsStore = useVtOptionsStore();
const loading = ref(false);
const options = ref([]);

// 单选模式的值
const singleValue = computed({
  get() {
    if (props.multiple) return "";
    return props.modelValue || "";
  },
  set(value) {
    emit("update:modelValue", value);
  },
});

// 选中的值（多选模式）
const selectedValues = computed({
  get() {
    if (!props.multiple) return [];
    if (props.type === "material") {
      // 对于材质类型，需要匹配选项中的value值
      return (props.modelValue || []).map((value) => {
        // 查找匹配的选项，可能是原始的材质名-厚度格式，也可能是用户修改后的格式
        const matchedOption = options.value.find((option) => {
          const materialName = option.value.split("-")[0];
          return value.startsWith(materialName + "-");
        });
        return matchedOption ? matchedOption.value : value;
      });
    }
    return Array.isArray(props.modelValue) ? props.modelValue : [];
  },
  set(value) {
    if (props.type === "material") {
      // 对于材质类型，保持用户自定义的厚度值
      const newValues = value.map((optionValue) => {
        const materialName = optionValue.split("-")[0];
        const existingValue = (props.modelValue || []).find((v) =>
          v.startsWith(materialName + "-")
        );
        return existingValue || optionValue; // 如果已有自定义厚度，保持；否则使用选项默认值
      });
      emit("update:modelValue", newValues);
    } else {
      emit("update:modelValue", value);
    }
  },
});

// 获取选项数据的方法映射
const storeMethodMap = {
  bagType: (filterType) => vtOptionsStore.getBagTypeOptions(filterType),
  compositeType: () => vtOptionsStore.getCompositeTypeOptions(),
  material: () => vtOptionsStore.getMaterialOptions(),
  size: () => vtOptionsStore.getSizeOptions(),
  surfaceFee: () => vtOptionsStore.getSurfaceFeeOptions(),
  accessory: () => vtOptionsStore.getAccessoryOptions(),
};

// 加载选项数据
async function loadOptions() {
  if (!storeMethodMap[props.type]) {
    console.warn(`VtRadioGroup: 不支持的类型 "${props.type}"`);
    return;
  }

  loading.value = true;
  try {
    if (props.type === "bagType") {
      options.value = await storeMethodMap[props.type](props.filterType);
    } else {
      options.value = await storeMethodMap[props.type]();
    }
  } catch (error) {
    console.error(`VtRadioGroup: 加载${props.type}选项失败`, error);
    options.value = [];
  } finally {
    loading.value = false;
  }
}

function handleChange(values) {
  if (props.type === "material") {
    // 对于材质类型，保持用户自定义的厚度值
    const newValues = values.map((optionValue) => {
      const materialName = optionValue.split("-")[0];
      const existingValue = (props.modelValue || []).find((v) => v.startsWith(materialName + "-"));
      return existingValue || optionValue;
    });
    const selectedOptions = options.value.filter((item) => values.includes(item.value));
    emit("change", newValues, selectedOptions);
  } else {
    const selectedOptions = options.value.filter((item) => values.includes(item.value));
    emit("change", values, selectedOptions);
  }
}

function handleSingleChange(value) {
  const selectedOption = options.value.find((item) => item.value === value);
  emit("change", value, selectedOption);
}

function handleThicknessChange(optionValue, thickness) {
  const materialName = optionValue.split("-")[0];
  const currentValues = props.modelValue || [];
  const newValues = currentValues.map((value) => {
    if (value.startsWith(materialName + "-")) {
      return `${materialName}-${thickness}`;
    }
    return value;
  });

  // 如果材质不在当前值中，添加它
  if (!currentValues.some((v) => v.startsWith(materialName + "-"))) {
    newValues.push(`${materialName}-${thickness}`);
  }

  emit("update:modelValue", newValues);
}

// 检查材质是否被选中
function isMaterialSelected(optionValue) {
  if (props.type !== "material") return false;
  const materialName = optionValue.split("-")[0];
  return (props.modelValue || []).some((value) => value.startsWith(materialName + "-"));
}

// 获取材质的厚度值
function getMaterialThickness(optionValue) {
  if (props.type !== "material") return 0;
  const materialName = optionValue.split("-")[0];
  const materialValue = (props.modelValue || []).find((value) =>
    value.startsWith(materialName + "-")
  );
  if (materialValue) {
    const parts = materialValue.split("-");
    return parseFloat(parts[1]) || 0;
  }
  return 0;
}

onMounted(() => {
  loadOptions();
});

// 监听type和filterType变化，重新加载数据
watch([() => props.type, () => props.filterType], () => {
  loadOptions();
});
</script>

<style scoped lang="scss">
.vt-radio-group {
  width: 100%;

  .radio-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    margin-right: 12px;

    .el-checkbox {
      margin-right: 12px;
    }

    .thickness-input {
      width: 120px;
      margin-left: 8px;
    }
  }

  :deep(.el-checkbox-group) {
    display: flex;
    flex-direction: column;
  }

  :deep(.el-checkbox) {
    margin-right: 0;
    margin-bottom: 0;
  }

  :deep(.el-radio-group) {
    display: flex;
    flex-direction: column;
  }

  :deep(.el-radio) {
    margin-right: 0;
    margin-bottom: 0;
  }
}
.vt-radio-group-start {
  :deep(.el-checkbox-group) {
    flex-direction: row;
  }

  :deep(.el-radio-group) {
    flex-direction: row;
  }
}
</style>
